/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sdkj.dspservice.common.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.dao.TreeDao;
import com.sdkj.dspservice.common.base.entity.TreeEntity;
import com.sdkj.dspservice.common.base.service.TreeService;
import com.sdkj.dspservice.common.utils.Reflections;
import com.sdkj.dspservice.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = true)
public class TreeServiceImpl<D extends TreeDao<T>, T extends TreeEntity<T>> extends CrudServiceImpl<D, T> implements TreeService<T> {

	@Transactional(readOnly = false)
	@Override
	public boolean saveOrUpdate(T entity) {

		boolean result;

		@SuppressWarnings("unchecked")
		Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);

		// 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
		T parent = null;
		if (StringUtils.isBlank(entity.getParentId())){
			entity.setParentId("0");
		}else {
			parent = dao.selectById(entity.getParentId());
		}

		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = entity.getParentIds();

		// 判断父节点是否存在
		if(parent != null){
			// 父节点存在，当前实体parentIds为：父节点的parentIds+父节点id
			entity.setParentIds(parent.getParentIds() + parent.getId() + ",");
		}else {
			// 父节点不存在，parentIds为：0,
			entity.setParentIds("0,");
		}

		// 如果没有写入顺序，则默认为于其平级的排序+30
		if(entity.getSort() == null){
			entity.setSort(30);
		}

		// 保存或更新实体
		result = super.saveOrUpdate(entity);

		// 更新子节点 parentIds
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("parent_ids", "," + entity.getId() + ",");
		List<T> list = dao.selectList(queryWrapper);
		for (T e : list){
			if (StringUtils.isNotBlank(e.getParentIds()) && StringUtils.isNotBlank(oldParentIds)){
				e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
				dao.updateById(e);
			}
		}

		return result;
	}

}
